#coding=utf8
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from django.contrib.auth.models import User

import datetime

from docshare.share.models import *
from docshare.share.tools import *
from docshare.share.forms import *

import settings

def login(request):
    return render_to_response('permission/index.html')

def logout(request):
    auth.logout(request)
    return HttpResponseRedirect("/%s"%settings.SITE_ROOT)

def relogin(request):
    return HttpResponseRedirect("/%s"%settings.SITE_ROOT)

#########################以下为docshare简单视图#####################################

def show_resource(request):
    object_list = list(catalog.objects.filter(parentId=0))#取根目录
    return render_to_response('resource/show_resource.html',{'object_list':object_list},context_instance=RequestContext(request))

def ajax_leveltwo_resource(request,catogry):
    obj=catalog.objects.get(id=catogry)
    return render_to_response('resource/leveltwo_ajax.html',{'obj':obj})

def pub_list(request):
    pub_list = pub.objects.all()
    return render_to_response('resource/pub_list_ajax.html',{'pub_list':pub_list})

def show_leveltwo_resource(request,catogry):
    obj=catalog.objects.get(id=catogry)
    return render_to_response('resource/show_leveltwo_resource.html',{'obj':obj},context_instance=RequestContext(request))

def show_files(request,catogry):
    obj = catalog.objects.get(pk=catogry)
    objects = pagerTool(request,upFile.objects.filter(cata=catogry,is_del=False))
    if request.method == 'POST':
        if not request.user.has_perm('share.add_upfile'):
            return HttpResponseRedirect('/%s/no_permission'%settings.SITE_ROOT)
        form = CataUpFileForm(request.POST,request.FILES)
        if form.is_valid():
            new_upFile = form.save(commit=False)
            new_upFile.size = request.FILES['filepath'].size
            new_upFile.user = request.user
            new_upFile.cata = obj
            new_upFile.save()
            #制作缩略图
            if new_upFile.filepic:
                from docshare import settings
                path = settings.DEFAULT_FILE_STORAGE_PATH + str(new_upFile.filepic)
                print path
                make_thumb(path)
#            return HttpResponseRedirect('/%s/resource/show_files/%s'%(settings.SITE_ROOT,catogry))
            return HttpResponse("success")#ajax通知浏览器已经完成
        return HttpResponse("fail");
    else:
        form=CataUpFileForm()
    return render_to_response('resource/show_files.html',{'objects':objects,'obj':obj,'form':form},context_instance=RequestContext(request))

def trash(request):
    objects = pagerTool(request,upFile.objects.filter(is_del=True))
    return render_to_response('resource/trash.html',{'objects':objects},context_instance=RequestContext(request))


def show_files_pic(request,catogry,type=0):
    obj = catalog.objects.get(pk=catogry)
    if type=='0':
        objects = pagerTool(request,upFile.objects.filter(cata=catogry))
    else:
        objects = pagerTool(request,upFile.objects.filter(cata=catogry).exclude(filepic=''))
    return render_to_response('resource/show_files_pic.html',{'objects':objects,'obj':obj},context_instance=RequestContext(request))


def show_files_context(request,fileId):
    file = upFile.objects.get(id=fileId)
    return render_to_response('resource/show_files_context.html',{'file':file},context_instance=RequestContext(request))

def file_midif(request):
    if request.method == 'POST':
        if not request.user.has_perm('share.add_upfile'):
            return HttpResponseRedirect('/%s/no_permission'%settings.SITE_ROOT)
        form = UpFileForm(request.POST,request.FILES)
        if form.is_valid():
            new_upFile=form.save(commit=False)
            new_upFile.size = request.FILES['filepath'].size
            new_upFile.user = request.user
            new_upFile.save()

            #制作缩略图
            if new_upFile.filepic:
                from docshare import settings
                path = settings.DEFAULT_FILE_STORAGE_PATH + str(new_upFile.filepic)
#                print path
                make_thumb(path)
#            return HttpResponseRedirect('/%s/resource/show_resource/'%settings.SITE_ROOT)
            return HttpResponse("success")#ajax通知浏览器已经完成
        return HttpResponse("fail");
    else:
        form=UpFileForm()
    return render_to_response('resource/upload_files.html',{'form':form},context_instance=RequestContext(request))


def user_info(request,id=0):
    message = ""
    obj = User.objects.get(pk=id)
    if obj and obj.id!=request.user.id:
        obj = None
        form_profile = ProfileForm()
    else:
        form_profile = ProfileForm(instance=obj.profile)

    if request.method == 'POST':
        old = request.POST.get('old_pass',None)
        new = request.POST.get('new_pass',None)
        if old and new:
            user = request.user
            if user.check_password(old):
                user.set_password(new)
                user.save()
                message = "用户密码修改成功！"
            else:
                message = "您的密码输入不正确，请重试！"
        else:
            form_profile = ProfileForm(request.POST,instance=obj.profile)
            if form_profile.is_valid():
                form_profile.save()
                message = "用户资料修改成功！"
    return render_to_response('resource/personal.html',{'form_profile':form_profile,'message':message,'obj':obj},context_instance=RequestContext(request))




def show_search(request):
    form = SearchForm()
    searchStr = request.GET.get('searchStr',None)
    cata = request.GET.get('cata',None)
    filetime = request.GET.get('filetime',None)
    prefix_two = request.GET.get('prefix_two',None)
    prefix_three = request.GET.get('prefix_three',None)
    if searchStr:
        objects = pagerTool(request,simpleSearch(searchStr,None,None,None,None))
        return render_to_response('resource/search.html',{'objects':objects,'form':form},context_instance=RequestContext(request))
    if cata != None:
        objects = pagerTool(request,simpleSearch(None,cata,filetime,prefix_two,prefix_three))
        return render_to_response('resource/search.html',{'objects':objects,'form':form},context_instance=RequestContext(request))
    return render_to_response('resource/search.html',{'form':form},context_instance=RequestContext(request))


###############################
#搜索辅助函数
def simpleSearch(searchStr,cata,filetime,prefix_two,prefix_three):
    if searchStr:
        obj = upFile.objects.filter(
                Q(name__contains=searchStr)|Q(about__contains=searchStr)
        )
    else:
        #按文件类型搜索
        if cata == '':
            obj = upFile.objects.all()
        else:
            obj = upFile.objects.filter(cata = cata)

        #按时间搜索
        if filetime !='':
            now_time = datetime.datetime.now()-datetime.timedelta(days=int(filetime))
            obj = obj.filter(datetime__gt=now_time)

        #按宣传类型搜索
        if prefix_two != '':
            obj = obj.filter(prefix_two=dictionaries.objects.get(pk=prefix_two))

        #按地市搜索
        if prefix_three != '':
            obj = obj.filter(prefix_three=dictionaries.objects.get(pk=prefix_three))
    return obj